package com.hrbxlh.actionImpl;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hrbxlh.dao.*;
import com.hrbxlh.pojo.Chapter;
import com.hrbxlh.vo.SkillDTO;
import com.hrbxlh.pojo.SkillNotes;
import com.hrbxlh.util.*;
import com.hrbxlh.virtualization.exception.GlobalException;
import com.hrbxlh.virtualization.result.*;
import com.hrbxlh.virtualization.service.CourseService;
import com.hrbxlh.virtualization.service.ImageAllocationService;
import com.hrbxlh.virtualization.service.impl.CourseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * -------------------------------------------------------
 * Copyright (c) 2017, 鑫联华信息科技股份有限公司
 * All rights reserved.
 * FileName：CourseActionImpl.java
 * Description：课程actionImpl类,负责操作课程数据以及逻辑处理。
 * History：
 * Date           Author               Desc
 * 2017.3.27		  xzx                 建立
 * -------------------------------------------------------
 */

@Component("courseActionImpl")
@Transactional
public class CourseActionImpl {

	@Resource(name="courseDao")
	private CourseDao courseDao;

	@Resource(name="chapterDao")
	private ChapterDao chapterDao;

	@Resource(name="homeworkTestDao")
	private HomeworkTestDao homeworkTestDao;

	@Resource(name="classDao")
	private ClassDao classDao;

	@Resource(name="relationDao")
	private RelationDao relationDao;

	@Resource(name="memberDao")
	private MemberDao memberDao;

	@Resource(name="sourceDao")
	private SourceDao sourceDao;

	@Resource(name="questionDao")
	private QuestionDao questionDao;

	@Resource(name = "coursePowerDao")
	private CoursePowerDao coursePowerDao;

    @Autowired
    @Qualifier("chapterActionImpl")
    private ChapterActionImpl chapterActionImpl;

	@Autowired
	private CourseService courseService;

	@Autowired
	private ImageAllocationService imageAllocationService;

	Logger logger = Logger.getLogger(CourseActionImpl.class.getName());

	/**
	 * @description 1025 跳转页面需要的方法，将需要的返回，将cookie信息返回
	 * @param req
	 * @param jsonStr
	 * @return String
	 */
	public Map<String, Object> getSkipPageMsg(HttpServletRequest req, String jsonStr)  {
		Map<String, Object> resultMap = Maps.newHashMap();
		//获取参数
		ObjectMapper mapper = new ObjectMapper();
		try {
			resultMap = mapper.readValue(jsonStr, resultMap.getClass());
			//获取登录人信息
			Map<String, Object> sessionValues = new SessionValues().getSessionValues(new String[]{"realRoleId","stuorteaId"}, req, "userMsg");
			resultMap.put("roleId", sessionValues.get("realRoleId"));
			resultMap.put("stuorteaId", sessionValues.get("stuorteaId"));
			resultMap.put("pageName",resultMap.get("pageName"));
		}catch(Exception e){
			e.printStackTrace();
			logger.error("跳转页面出现异常getSkipPageMsg", e);
			return (Map<String, Object>) new HashMap<String, Object>().put("pageName","public/pageerror");
		}
		return resultMap;
	}


	/**
	 * @description 添加课程的方法，需要课程名，副标题，封面颜色，讲师，简介
	 * @param  paramMap
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public Map<String, Object> addCourse(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, Object> nameMap = courseDao.getCourseDetailByName(paramMap);
			if(nameMap == null){
				String introction = (String)paramMap.get("courseIntroduction");
				introction = introction.replaceAll("\n", "<br>");
				introction = introction.replaceAll("\r", "<br>");
				paramMap.put("courseIntroduction", introction);
				//添加课程
				Map<String, Object> colorAndMarkMap = PubMethods.getColorAndMark();
				paramMap.put("courseTitle", colorAndMarkMap.get("mark"));
				paramMap.put("courseColer", colorAndMarkMap.get("color"));
				//获取课程名的首字母缩写
				ChineseCharToEn cte = new ChineseCharToEn();
				String couserChineseChar = cte.getAllFirstLetter(String.valueOf(paramMap.get("courseName"))).toUpperCase();
				paramMap.put("couserChineseChar",couserChineseChar);
				courseDao.addCourse(paramMap);
				//返回添加的课程信息
				Map<String, Object> detailMap = courseDao.getCourseDetail(paramMap);
				map.put("detailMsg", detailMap);
				//将添加的课程信息保存到中间表中
				detailMap.put("inMark", 1);
				detailMap.put("selectMark", 1);
				courseDao.addRelTeaCourse(detailMap);
				//给当前教师和当前课程创建权重
				paramMap.put("classPerformance",0.4);
				paramMap.put("excellent",100);
				paramMap.put("good",90);
				paramMap.put("inso",80);
				paramMap.put("bad",60);
				paramMap.put("souceMark",0);
				//查询这个教师这个课程是否已经存在权重
				Map<String,Object> sourceMap = sourceDao.getProWedith(paramMap);
				if(sourceMap==null||sourceMap.size()==0){
					sourceDao.addSorceSet(paramMap);
				}
				map.put("resultFlag", true);
			}else{
				map.put("resultFlag", false);
				map.put("failMsg", "课程名称已存在");
			}
		} catch (Exception e) {
			map.put("resultFlag", false);
			logger.error("添加课程异常addCourse", e);
			throw e;
		}
		return map;
	}

	/**
	 * @description 添加课程与章节的关联信息    没写rap
	 * @param jsonStr courseId
	 *  章节列表信息 属性：chapterList  字段[{"chapterId":1,"chapterNum":1}...]
	 * */
	@Transactional
	public void addCourseReChapters(HttpServletResponse res,HttpServletRequest request, String jsonStr){
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map = mapper.readValue(jsonStr, map.getClass());
			//获取当前登录人id
			String stuorteaId = PubMethods.loginId(request);

			//判断前台传的新集合与就集合是否一样，在有学习记录的情况下确保不是删除和修改，添加可以
			List<Map<String,Object>> chapterList= (List<Map<String, Object>>)map.get("chapterList");
			List<Integer> oldList= (List<Integer>)map.get("oldList");
			Map<String,Object> sameMap = isSame(chapterList,oldList);
			boolean sameFlag = (boolean) sameMap.get("flag");
			List<Integer> ImagAddList = (List<Integer>) sameMap.get("addList");
			List<Integer> ImagdelList = (List<Integer>) sameMap.get("delList");
			if(!sameFlag){
				//判断是否有这个课的学习记录信息
				if(!CollectionUtils.isEmpty(courseDao.getStudyList(map))){
					map.put("result", "fail");
					map.put("failMsg", "已存在学习记录信息不可修改");
					responseStream(res, mapper.writeValueAsString(map));
					return;
				}
				//判断是否有关于这个课的作业信息
				if(!CollectionUtils.isEmpty(homeworkTestDao.getTaskByCourseId(map))){
					map.put("result", "fail");
					map.put("failMsg", "已存在作业或实验信息不可修改");
					responseStream(res, mapper.writeValueAsString(map));
					return;
				}
			}

			//1025判断章节是否重复
			if(!this.checkRepeatFunc((List<Map<String, Object>>)map.get("chapterList"), "chapterId")){
				map.put("result", "fail");
				map.put("failMsg", "章节重复");
				responseStream(res, mapper.writeValueAsString(map));
				return ;
			}

			//调用王晨的方法
			imageAllocationService.confirmImageAllocation(Integer.parseInt(String.valueOf(map.get("courseId"))),ImagAddList);
			if(ImagdelList!=null&&ImagdelList.size()!=0){
				imageAllocationService.cancelImageAllocation(Integer.parseInt(String.valueOf(map.get("courseId"))),ImagdelList);
			}
			//删除这个课程与章节的关联信息
			courseDao.delCourseReChapter(map);
			//如果表单中没有选择章节信息，就不添加关联
			if(chapterList != null && chapterList.size() != 0){
				//最后加入关联信息的集合
				List<Map<String,Object>> finalChapterList = new ArrayList<>();
				//查询传过来所有章节的基本信息
				List<Map<String,Object>> noChapterList = chapterDao.getChapterByListId(map);
				//将传过来的章节与查出来的章节信息进行合并
				List<Map<String,Object>> finalList = coverList(noChapterList,chapterList);
				for (int i=0;i<finalList.size();i++){
					//查询要保存的章节是否是当前登录人创建的
					finalList.get(i).put("coursemark",1);
					Map<String, Object> chapterMap = chapterDao.getOneChapter(finalList.get(i));
					//要保存章节的原制作人id
					String chapterTeaId = String.valueOf(chapterMap.get("stuorteaId"));
					int chaperId = 0;
					Map<String,Object> finalMap = new HashMap<>();
					Chapter chapter =chapterActionImpl.getParam(finalList.get(i));
					//判断当前登录人是否已经复制过此章节
					map.put("stuorteaId",stuorteaId);
					map.put("chapterName",finalList.get(i).get("chapterName"));
					map.put("courseMark",finalList.get(i).get("courseMark"));

					if(!chapterTeaId.equals(stuorteaId)){
						//将当前登录人原来创作过的章节删除
						chapterDao.delChapterByChapNameAndSid(map);
						//将制作人放入
						chapter.setStuorteaId(stuorteaId);
						chapter.setTestAddress("");
						chapterDao.addChapter(chapter);
						chaperId = chapter.getChapterId();
						//说明要保存的章节不是当前登录人创建的，则需要改章节编号
						//将赋值的章节编号改成相应的
						String courseMark = "ZDY•"+String.valueOf(chaperId);
						finalMap.put("courseMark",courseMark);
						finalMap.put("chapterId",chaperId);
						//更改chapter，将课程标识加进去（20180817将课程标识改成自定义+章节id了，所以在创建章节的时候就可以生成了）
						courseDao.updatChapterCousrMark(finalMap);
					}else{
						chaperId = Integer.parseInt(String.valueOf(finalList.get(i).get("chapterId")));
					}
					finalMap.put("chapterId",chaperId);
					finalMap.put("chapterNum",finalList.get(i).get("chapterNum"));
					finalChapterList.add(finalMap);
				}
				map.put("chapterList",finalChapterList);
				//添加关联
				courseDao.addCourseReChapter(map);
			}
			map.put("result", "success");
			responseStream(res, mapper.writeValueAsString(map));
			logger.info("添加课程章节关联,参数为："+jsonStr);
		} catch (Exception e) {
			logger.error("添加课程章节关联异常addCourseReChapters", e);
			e.printStackTrace();
			map.put("result", "fail");
			try {
				responseStream(res, mapper.writeValueAsString(map));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}

	private Map<String,Object> isSame(List<Map<String,Object>> chapterList,List<Integer> oldList){
		//两个集合的相同的个数
		int sameCount = 0;
		Map<String,Object> returnMap = new HashMap<>();
		List<Integer> newList = new ArrayList<>();
		for(int i=0;i<chapterList.size();i++){
			newList.add(Integer.parseInt(String.valueOf(chapterList.get(i).get("chapterId"))));
			for(int j=0;j<oldList.size();j++){
				if(Integer.parseInt(String.valueOf(chapterList.get(i).get("chapterId")))==oldList.get(j)){
					sameCount = sameCount+1;
				}
			}
		}
		if(sameCount>=oldList.size()){
			returnMap.put("flag",true);
			returnMap.put("addList",newList);
		}if(sameCount<oldList.size()){
			returnMap.put("flag",false);
			//说明有删除
			oldList.removeAll(newList);
			returnMap.put("delList",oldList);
		}

		return returnMap;
	}

	/**
	 * 对比将新加的章节号插入最后要的集合中
	 * @param noChapterList 通过章节id查章节基本信息
	 * @param chapterList   要复制的章节
	 * @return
	 */
	private List<Map<String,Object>> coverList(List<Map<String,Object>> noChapterList,List<Map<String,Object>> chapterList){
		try {
			for (int i=0;i<noChapterList.size();i++){
				for (int j=0;j<chapterList.size();j++){
					if(Integer.parseInt(String.valueOf(noChapterList.get(i).get("chapterId")))==Integer.parseInt(String.valueOf(chapterList.get(j).get("chapterId")))){
						noChapterList.get(i).put("chapterNum",chapterList.get(j).get("chapterNum"));
						noChapterList.get(i).put("courseMark",chapterList.get(j).get("courseMark"));
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return noChapterList;
	}


	/**
	 * @description 获取课程信息，参数是主键
	 * @param  paramMap
	 * @return Map<String,Object>
	 * @throws Exception
	 */
	public Map<String, Object> getCourseDetail(Map<String, Object> paramMap,HttpServletRequest request) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			//返回信息
			map = courseDao.getCourseDetail(paramMap);
			//用课程id与学号查询进度信息
			map.put("stuorteaId", sessionValues.get("stuorteaId"));
			Map<String, Object> processMap = courseDao.getMyCourseProcess(map);
			map.put("courseProcess", processMap.get("courseProcess"));
		} catch (Exception e) {
			logger.error("获取课程信息getCourseDetail", e);
			throw e;
		}
		return map;
	}

	/**
	 * @description 修改课程
	 * @param  paramMap
	 * @return Map<String,Object>
	 * @throws Exception
	 */
	public Map<String, Object> saveCourse(Map<String, Object> paramMap) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		try {
			//20180427商莹改----当修改课程时将试卷名也相应修改
			//通过课程id查询此课程对应的试卷
			//20180510不需要改了因为生成试卷那改成输入试卷名了
			/*List<Map<String,Object>> onlineQuestionList = (List<Map<String, Object>>) questionDao.getOnlineQuestionByOnCourseId(paramMap);
			if(onlineQuestionList!=null&&onlineQuestionList.size()!=0){
				//将相应试卷名改成新的并将服务器文件名也相应改掉
				String[] keysArray = {"tomcatUrl", "project_name","server_address"};
				Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
				String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/question"+"/";
				List<Map<String,Object>> onlineQuestionFinalList = onlineQuestionList(onlineQuestionList,String.valueOf(paramMap.get("courseName")),path);
				//改数据库文件名
				questionDao.updateFileName(onlineQuestionFinalList);
			}*/
			Map<String, Object> listMap = courseDao.getCourseDetailByName(paramMap);
			if(listMap == null){
				//查询当前此课程是否有选课类型
				Map<String, Object> courseDetail = courseDao.getCourseDetail(paramMap);
				if(courseDetail != null && (Integer.parseInt(courseDetail.get("selectMark").toString()) == 2 || Integer.parseInt(courseDetail.get("selectMark").toString()) == 3)){
					//查询当前选课的学生数量
					int selectNum = courseDao.getSelectNum(paramMap);
					if(paramMap.get("maxStu") != null && Integer.parseInt(paramMap.get("maxStu").toString()) < selectNum){
						map.put("result", false);
						map.put("failMsg", "选课班学生人数少于当前选课学生数量，请重新填写");
						return map;
					}
				}
				String introction = (String)paramMap.get("courseIntroduction");
				introction = introction.replaceAll("\n", "<br>");
				introction = introction.replaceAll("\r", "<br>");
				paramMap.put("courseIntroduction", introction);
				courseDao.saveCourse(paramMap);
				map.put("result", true);
			}else{
				map.put("result", false);
				map.put("failMsg", "课程名称已存在");
			}
			logger.info("修改课程参数为："+paramMap.toString());
		} catch (Exception e) {
			throw e;
		}
		return map;
	}

	/**
	 * 修改文件名
	 */
	public List<Map<String,Object>> onlineQuestionList(List<Map<String,Object>> onlineQuestionList,String courseName,String url){
		List<Map<String,Object>> finalList = new ArrayList<>();
		//获取当前时间戳
		long nowTime = System.currentTimeMillis();
		for (Map<String,Object> mapOne:onlineQuestionList){
			Map<String,Object> finalMap = new HashMap<>();
			//原试卷名
			String beforeName = String.valueOf(mapOne.get("fileName"));
			//将原试卷名中的教师主键取出来
//			String[] arr = beforeName.split("&");
//			String stuorteaId = arr[1].substring(0,arr[1].lastIndexOf("."));
			//将新的试卷名拼接好
			String newName = courseName+"&"+nowTime+".doc";
			finalMap.put("newfileName",newName);
			finalMap.put("beforefileName",beforeName);
			finalMap.put("onlinequestionId",mapOne.get("onlinequestionId"));
			finalList.add(finalMap);
		}
		//将服务器对应的文件名称改了
		PubMethods.updateFileNames(url,finalList);
		return finalList;
	}

	/**
	 * @description 获取登录人所属院系的所有专业信息
	 * @param  paramMap  工号
	 * @return List<Map<String,Object>>
	 * @throws Exception
	 */
	public List<Map<String, Object>> getMyProfessionList(Map<String, Object> paramMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = courseDao.getMyProfessionList(paramMap);
		}catch(Exception e){
			logger.error("获取登录人所属院系的所有专业信息异常getMyProfessionList", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 查询某教师教的课程列表
	 * @param  paramMap Map<String,Object>
	 * @return List courseId课程id courseName课程名称
	 * @throws Exception
	 */
	public List<Map<String,Object>> getTeaTeachCourse(Map<String, Object> paramMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = courseDao.getTeaTeachCourse(paramMap);
		}catch(Exception e){
			logger.error("查询某教师教的课程列表异常getTeaTeachCourse", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 删除课程时判断是否与能力有关联
	 * @param  paramList 课程id集合 List<String>
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public Map<String,Object> delCourseHivePower(List<String> paramList) throws Exception {

		String failMsg = "";
		Map<String,Object> returnMap = new HashMap<>();
		try {
			//判断要删除的课程是否已经与能力有关联
			List<Map<String,Object>> coursePowerList = coursePowerDao.getRelCoPoListByCourseList(paramList);
			if(coursePowerList!=null&&coursePowerList.size()!=0){
				for (int i=0;i<coursePowerList.size();i++){
					if(i==coursePowerList.size()-1){
						failMsg+=coursePowerList.get(i).get("courseName");
					}else{
						failMsg+=coursePowerList.get(i).get("courseName")+",";
					}

				}
				returnMap.put("resultFlag",false);
				returnMap.put("failMsg","删除"+failMsg+"课会影响能力的课程权重是否确认删除？");
			}else {
				returnMap.put("failMsg","");
				returnMap.put("resultFlag",true);
			}
			logger.info("删除课程，参数为："+paramList.toString());
		} catch (Exception e) {
			logger.error("删除课程异常delCourse", e);
			throw e;
		}
		return returnMap;
	}

	/**
	 * @description 删除课程的方法，传的是每个课程的id。
	 * @param  paramList 课程id集合 List<String>
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public Map<String,Object> delCourse(List<String> paramList) throws Exception {

		boolean resultFlag = false;
		Map<String,Object> returnMap = new HashMap<>();
		try {
			//判断要删除的课程是否已经与能力有关联
			/*List<Map<String,Object>> coursePowerList = coursePowerDao.getRelCoPoListByCourseList(paramList);
			if(coursePowerList!=null&&coursePowerList.size()!=0){
				returnMap.put("failMsg","您要删除的课程中会影响能力的课程权重");
			}else {
				returnMap.put("failMsg","");
			}*/
			//3.0删除作业信息
			//获取这个课的所有作业信息
			List<Map<String, Object>> workList = courseDao.getWorkByCourseId(paramList);
			DelWorkFileUtil delWorkFileUtil = new DelWorkFileUtil();
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/stuwork/";
			//删除作业信息
			delWorkFileUtil.delFileList(workList, new String[] {"taskAddress", "convertFile"}, url);
			//0510删除教师与班级的关联关系
			courseDao.delTeaReClass(paramList);
			//0510删除学生与选课班级的关联信息
			courseDao.delStuReSelectClass(paramList);
			//0510删除选课班级的信息
			courseDao.delSelectClass(paramList);
			//删除课程
			courseDao.delCourse(paramList);
			//删除课程对应的章节信息
			courseDao.delChapterReLation(paramList);
			//删除课程表信息
			courseDao.delChassTab(paramList);
			//删除课程与班级的对应关系
			courseDao.delCourseClass(paramList);
			//删除学生与课程的对应关系
			courseDao.delStuCourse(paramList);
			//删除考试与课程的对应关系
			courseDao.delCourseExam(paramList);
			//删除问题与课程的关系
			courseDao.delCourseProblem(paramList);
			//删除作业信息
			courseDao.delHomework(paramList);
			//删除题库信息
			courseDao.delCourseQuestion(paramList);
			//删除学生学习历史信息
			courseDao.delUserStudyHistory(paramList);
			//删除classRelation表中的数据  参数是courseId
			classDao.delClassRelationsByCIds(paramList);
			//删除学生笔记信息
			homeworkTestDao.delNoteByCourseIds(paramList);
			//删除教师的这个课的等级的信息sorce
			sourceDao.delSorceByCourseIds(paramList);
			//删除答题信息onlinequestion 也写在sorce里
			sourceDao.delOnlineQuestionByCourseIds(paramList);
			//删除式样相关信息--调用王晨接口
//			courseDao.delExperiPeriodByCourseIds(paramList);
			List<Integer> intList = new ArrayList<>();
			for (int i=0;i<paramList.size();i++){
				intList.add(Integer.parseInt(String.valueOf(paramList.get(i))));
			}
			courseService.deleteContainersByCourseId(intList);
			courseService.deleteImageAllocationByCourseId(intList);
			courseService.deleteStatisticByCourseId(intList);
			//删除这些课程的学生的实验报告信息（保存上的）
			Map<String, Object> delMap = new HashMap<String, Object>();
			delMap.put("list", paramList);
			delMap.put("delType", 4);
			homeworkTestDao.delStuTestHistory(delMap);
			//20180710删除课程与能力值的关联
			coursePowerDao.delRelCoPoByCoureseList(paramList);
			resultFlag = true;
			returnMap.put("resultFlag",resultFlag);
			returnMap.put("failMsg","");
			logger.info("删除课程，参数为："+paramList.toString());
		} catch (Exception e) {
			logger.error("删除课程异常delCourse", e);
			throw e;
		}
		return returnMap;
	}

	/**
	 * @description 清空进度信息的方法
	 * @param paramMap 课程id
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public boolean emptyProcess(Map<String, Object> paramMap) throws Exception {

		boolean resultFlag = false;
		try {
			//清除进度信息
			courseDao.emptyProcess(paramMap);
			//清除学习信息（学号，课程号）
			courseDao.delMyStudyHistory(paramMap);
			resultFlag = true;
		} catch (Exception e) {
			logger.error("清空进度信息异常emptyProcess", e);
			throw e;
		}
		return resultFlag;
	}

	/**
	 * @description 添加进度信息的方法
	 * @param paramMap 课程id
	 * @return boolean (true 成功 ,false失败)
	 * @throws Exception
	 */
	public boolean addProcess(Map<String, Object> paramMap) throws Exception {

		boolean resultFlag = false;
		try {
			//获取原来他自己的进度信息
			Map<String, Object> processDetail = courseDao.getMyCourseProcess(paramMap);
			long process = (Long)processDetail.get("courseProcess");
			long comCourseCount = process += 1;
			int chapterNum = Integer.parseInt(paramMap.get("chapterNum").toString());
			paramMap.remove("chapterNum");
			//如果比所有的章节数都长就相等
			List<Map<String, Object>> chapterListAll = chapterDao.getCourseChapter(paramMap);
			if(chapterListAll != null && chapterListAll.size() != 0){
				int chapterLength = chapterListAll.size();
				if(process > chapterLength){
					process = chapterLength;
				}
			}
			processDetail.put("courseProcess", process);
			//进入课程次数
			processDetail.put("comCourseCount", comCourseCount);
			//添加进度信息
			processDetail.put("chapterNum", chapterNum);
			processDetail.put("stuorteaId", paramMap.get("stuorteaId"));
			processDetail.put("courseId", paramMap.get("courseId"));
			courseDao.addProcess(processDetail);
			//添加学习章节信息
			paramMap.put("chapterNum", chapterNum);
			List<Map<String, Object>> chapterList = courseDao.getMyStudyChapterList(paramMap);
			if(chapterList == null || chapterList.size() == 0){
				//获取登录人与这个课的关联标识
				Map<String, Object> relationMap = homeworkTestDao.getRelationMark(paramMap);
				paramMap.put("couSelectMark", relationMap.get("couSelectMark"));
				courseDao.addMyStudyHistory(paramMap);
			}
			resultFlag = true;
		} catch (Exception e) {
			logger.error("添加进度异常addProcess", e);
			throw e;
		}
		return resultFlag;
	}

	public boolean addCourseOrExpreCount(Map<String, Object> paramMap) throws Exception {

		boolean resultFlag = false;
		try {
			Map<String, Object> processDetail = new HashMap<>();
			//获取某个课程原来他自己的阅读课件和进入实验环境的次数
			paramMap.put("courseMark",1);
			List<Map<String, Object>> processDetailTwo = courseDao.getMyCourseCourseOrExpreCount(paramMap);
			long readCourseCount = Long.parseLong(String.valueOf(processDetailTwo.get(0).get("readCourseCount")));
			long comExpreCount = Long.parseLong(String.valueOf(processDetailTwo.get(0).get("comExpreCount")));
			if(Integer.parseInt(String.valueOf(paramMap.get("mark")))==1){
				readCourseCount +=1;
			}if(Integer.parseInt(String.valueOf(paramMap.get("mark")))==2){
				comExpreCount +=1;
			}
			processDetail.put("comExpreCount", comExpreCount);
			processDetail.put("readCourseCount", readCourseCount);
			processDetail.put("courseId", paramMap.get("courseId"));
			processDetail.put("stuorteaId", paramMap.get("stuorteaId"));
			courseDao.addCourseOrExpreCount(processDetail);
			resultFlag = true;
		} catch (Exception e) {
			logger.error("增加阅读课件、进入实验环境的次数addCourseOrExpreCount", e);
			throw e;
		}
		return resultFlag;
	}

	/**
	 * @description 获取学生或教师学习了的章节的信息
	 * @param  paramMap 工号或学号   课程号 Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public List<Map<String,Object>> getMyStudyChapterList(Map<String, Object> paramMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = courseDao.getMyStudyChapterList(paramMap);
		}catch(Exception e){
			logger.error("获取学习的章节信息异常getMyStudyChapterList", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 获取某专业下的课程信息
	 * @param  paramMap 专业id Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public List<Map<String,Object>> getCourseByProfessionId(Map<String, Object> paramMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = courseDao.getCourseByProfessionId(paramMap);
		}catch(Exception e){
			logger.error("获取某专业下的课程信息异常getCourseByProfessionId", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 修改课程的选课标识
	 * @param  paramMap 课程id 1（不是选课的）或2（选课的课程）  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public boolean saveSelectMark(Map<String, Object> paramMap) throws Exception{

		boolean result = false;
		try{
			courseDao.saveSelectMark(paramMap);
			result = true;
		}catch(Exception e){
			logger.error("修改课程的选课标识异常saveSelectMark", e);
			throw e;
		}
		return result;
	}

	/**
	 * @description 获取某个人的学习进度信息
	 * @param  paramMap 课程id 学号  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String, Object> getMyStudyProcess(Map<String, Object> paramMap) throws Exception{

		Map<String, Object> map = new HashMap<String, Object>();
		try{
			map = courseDao.getMyStudyProcess(paramMap);
		}catch(Exception e){
			logger.error("获取某个人的学习进度信息异常getMyStudyProcess", e);
			throw e;
		}
		return map;
	}

	/**
	 * @description 查询我的消息列表
	 * @param request
	 * @return List
	 * @throws Exception
	 */
	public List<Map<String,Object>> getMyNotice(HttpServletRequest request) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			//获取登录人信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request, "userMsg");
			list = courseDao.getMyNotice(sessionValues);
		}catch(Exception e){
			logger.error("查询我的消息列表异常getMyNotice", e);
			throw e;
		}
		return list;
	}


	/**
	 * @description 查询我的班级对应课程的列表（结课管理）
	 * @param  paramMap 工号 Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String,Object> getMyClassCourseList(Map<String,Object> paramMap) throws Exception{

		Map<String, Object> map = new HashMap<String,Object>();
		try{
			int pageNow = Integer.parseInt(paramMap.get("pageNow").toString());
			int pageSize = Integer.parseInt(paramMap.get("pageSize").toString());
			int startNum = pageUtil.getSqlStartPos(pageNow, pageSize);
			paramMap.put("startNum", startNum);
			//获取列表信息
			List<Map<String, Object>> classCourseList = courseDao.getMyClassCourseList(paramMap);
			map.put("classCourseList", classCourseList);
			map.put("pageNow", pageNow);
			//获取全部页数
			paramMap.put("pageNow", 0);
			paramMap.put("startNum", 0);
			List<Map<String, Object>> allList = courseDao.getMyClassCourseList(paramMap);
			int totalPage = pageUtil.getTotalPage(allList, pageSize);
			map.put("totalPage", totalPage);
		}catch(Exception e){
			logger.error("查询我的班级对应课程的列表异常getMyClassCourseList", e);
			throw e;
		}
		return map;
	}

	/**
	 * @description 将某班级对应的某课程进行完结
	 * @param  paramMap 课程id 1（不是选课的）或2（选课的课程）  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String, Object> endCourseClass(Map<String, Object> paramMap, HttpServletRequest request) throws Exception{

		Map<String, Object> returnMap = new HashMap<>();
		try{
			List<String> listOne = new ArrayList<>();
			listOne.add(String.valueOf(paramMap.get("classId")));
			List<Map<String, Object>> classListOne = classDao.getClassStateList(listOne);
			if(classListOne!=null&&classListOne.size()!=0){
				returnMap.put("result",false);
				returnMap.put("failMsg","班级处于考试状态不可解除任课");
				return returnMap;
			}
			//获取登录人信息
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"userName","stuorteaId"}, request, "userMsg");
			paramMap.put("classEndMark", 1);
			courseDao.endCourseClass(paramMap);
			//0626查询这个班级的全部信息
			Map<String, Object> classMap = classDao.getClassNameById(paramMap);
			//如果是选课的班级，需要将这个课程变为正常的课，并且删除这个课程的选课班级信息
			if(Integer.parseInt(classMap.get("classMark").toString()) == 1){
				paramMap.put("selectMark", 1);
				courseDao.saveSelectMark(paramMap);
				//修改新加的字段标识，将class表中这个班级的新加标识改为已结课
				//paramMap.put("useMark", 1);
				//classDao.saveUseMark(paramMap);
				//将这个班级下的学生与这个课程的关联的结课标识改为1
				classDao.saveEndMarkEnd(paramMap);
			}
//			//删除这个班级信息
//			List<String> idList = new ArrayList<String>();
//			idList.add(paramMap.get("classId").toString());
//			classDao.delClass(idList);
//			//删除这个课程与这个选课班级的关联信息
//			relationDao.delCourseReClass(paramMap);

			//如果这个课的上课老师有两种都上的，如果，classMark是1 就改为1 如果是0 改为2
			Map<String, Object> teacherMsg = relationDao.getTeachAllTeacherByCourseId(paramMap);
			if(teacherMsg != null){
				//如果是选课的班级，把老师与这个课的mark变为1
				if(Integer.parseInt(classMap.get("classMark").toString()) == 1){
					teacherMsg.put("selectMark", 1);
					relationDao.saveSelectMark(teacherMsg);
					//如果是正常的班级，把mark改为2
				}else{
					//如果这个课程与这个老师正常类型无关联，就改为2
					paramMap.put("stuorteaId", sessionValues.get("stuorteaId"));
					List<Map<String, Object>> teacherReCourseList = relationDao.getTeachMsgIdByCouIdSid(paramMap);
					if(teacherReCourseList == null || teacherReCourseList.size() == 0){
						teacherMsg.put("selectMark", 2);
						relationDao.saveSelectMark(teacherMsg);
					}
				}
			}
			//删除classrelation中这个课，这个班，这个老师之间的关联

			//sessionValues.put("classId", paramMap.get("classId"));
			//sessionValues.put("courseId", paramMap.get("courseId"));
			//classDao.delClassRelation(sessionValues);

			//0626end
			//3.0查询这个班级下所有学生这个课的作业信息
			List<Map<String, Object>> workList = courseDao.getStuWorkByCourseIdAndClassId(paramMap);
			DelWorkFileUtil delWorkFileUtil = new DelWorkFileUtil();
			//文件前缀路径
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/stuwork/";
			//删除这些学生的作业文件
			delWorkFileUtil.delWorkFile(workList, "taskAddress","convertFile", url);
			//0319修改task结课之后的数据信息
			//查询某个班某个课的学生的数据信息 courseId classId
			List<Map<String, Object>> stuTaskList = homeworkTestDao.getCourseClassStuTask(sessionValues);
			//按照每条去修改数据
			if(!CollectionUtils.isEmpty(stuTaskList)){
				for(Map<String, Object> stuTaskMap : stuTaskList){
					stuTaskMap.put("endClassId", paramMap.get("classId"));
					stuTaskMap.put("endTeacherId", sessionValues.get("stuorteaId"));
					homeworkTestDao.updateTaskEndMarkColumn(stuTaskMap);
				}
			}
			//3.0删除这个班级下的所有学生的这个课的作业信息
			homeworkTestDao.delTaskByCourseIdAndClassId(paramMap);
			returnMap.put("result",true);
			returnMap.put("failMsg","");
		}catch(Exception e){
			logger.error("班级结课异常endCourseClass", e);
			throw e;
		}
		return returnMap;
	}

	/**
	 * @description 通过课程，章节，查询课程课件信息
	 * @param  paramMap 课程id 章节id  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String, Object> getChapterByCourseId(Map<String, Object> paramMap,HttpServletRequest request) throws Exception{

		Map<String, Object> map = new HashMap<String, Object>();
		try{
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues =session.getSessionValues(new String[]{"roleId","stuorteaId"}, request, "userMsg");
			int roleId = Integer.parseInt(sessionValues.get("roleId").toString());
			paramMap.put("roleId",roleId);
			paramMap.put("stuorteaId",sessionValues.get("stuorteaId"));
			map = courseDao.getChapterByCourseId(paramMap);
		}catch(Exception e){
			logger.error("查询某课程章节课件信息异常getChapterByCourseId", e);
			throw e;
		}
		return map;
	}

	/**
	 * @description 查询所有课程
	 * @return List
	 * @throws Exception
	 */
	public List<Map<String, Object>> getAllCourse(Map<String, Object> preParamMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try{
			list = courseDao.getAllCourse(preParamMap);
		}catch(Exception e){
			logger.error("查询所有课程异常", e);
			throw e;
		}
		return list;
	}

	/**
	 * 查看是否有学习记录
	 */
	private boolean getStudyHistory(Map<String,Object> paramMap){
		try {
			List<Map<String,Object>> homeworkOrExpreList = chapterDao.getHomeworkListByChapterId(paramMap);
			if(homeworkOrExpreList!=null&&homeworkOrExpreList.size()!=0){
				return false;
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * @description 删除作业，视频的方法
	 * @param  delHomework, delVideo, courseId , chapterId  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public boolean delHomeworkOrVideo(String delHomework, String delVideo, long chapterId, String delCourseware, String delPackageFile,String delExprement,String delMaterial,String delTest) throws Exception{

		boolean result = true;
		try{
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("chapterId", chapterId);
			paramMap.put("coursemark",1);
			Map<String, Object> chapterDetail = chapterDao.getOneChapter(paramMap);
			//获取文件前缀
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/course/";
			FileUpload fileUpload = new FileUpload();
			//如果删除了作业
			if(delHomework.equals("true")){
				//判断当前章节是否已经有学习记录
				paramMap.put("taskType",1);
				boolean flag = getStudyHistory(paramMap);
				if(!flag){
					return false;
				}
				paramMap.put("type", 3);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将tasklibrary表相应数据删除
				chapterDao.delTaskLibrary(Integer.parseInt(String.valueOf(paramMap.get("chapterId"))));
				//将文件删除
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("homeworkNameDoc"));
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("homeworkName"));
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("homeworkNameHtml"));
			}
			//如果删除了实验报告
			if(delExprement.equals("true")){
				//判断当前章节是否已经有学习记录
				paramMap.put("taskType",2);
				boolean flag = getStudyHistory(paramMap);
				if(!flag){
					return false;
				}
				paramMap.put("type", 4);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将exprelibrary表相应数据删除
				chapterDao.delExpreLibrary(Integer.parseInt(String.valueOf(paramMap.get("chapterId"))));
			}
			//如果删除了视频
			if(delVideo.equals("true")){
				paramMap.put("type", 2);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将文件删除
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("videoName"));
			}
			//如果删除了备课材料
			if(delMaterial.equals("true")){
				paramMap.put("type", 5);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将文件删除
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("courseMaterialName"));
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("courseMaterialNameHtml"));
			}
			//如果删除了实验手册
			if(delTest.equals("true")){
				paramMap.put("type", 7);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将文件删除
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("testDocName"));
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("testNameHtml"));
			}
			//如果删除了课件
			if(delCourseware.equals("true")){
				paramMap.put("type", 8);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将文件删除
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("coursewareName"));
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("coursewareNameHtml"));
			}
			//如果删除了课程材料
			if(delPackageFile.equals("true")){
				paramMap.put("type", 9);
				//将字段清空
				chapterDao.delChapterCoHoVo(paramMap);
				//将文件删除
				fileUpload.deleteFileOnly(url, (String)chapterDetail.get("packageFile"));
			}
		}catch(Exception e){
			logger.error("删除课件异常delHomeworkOrVideo", e);
			throw e;
		}
		return result;
	}

	/**
	 * @description 获取某个老师教的全部课程
	 * @param  paramMap 工号  Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public List<Map<String,Object>> getMyClasses(Map<String, Object> paramMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = courseDao.getMyClasses(paramMap);
		}catch(Exception e){
			logger.error("获取某个老师教的全部课程异常getMyClasses", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 查询课程及每个课程的章节信息  （分为预置的和非预置进去的,用saveMark标识）
	 * @param paramMap Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public List<Map<String,Object>> getCourseList(Map<String, Object> paramMap) throws Exception{


		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			//预置的
			if(Integer.parseInt(paramMap.get("saveMark").toString()) == 1){
				//查询预置全部课程
				paramMap.put("releaseMark",1);
				paramMap.put("shareMark",1);
				List<Map<String, Object>> courseList = courseDao.getAllCourseMy(paramMap);
				//查询每个课程里面的章节信息
				if(courseList != null){
					for(Map<String, Object> map : courseList){
						//查询这个课程下的章节信息只要id名字，num
						List<Map<String, Object>> chapterList = chapterDao.getCourseChapter(map);
						map.put("chapterList", chapterList);
					}
					list = courseList;
				}
				//非预置的
			}else if(Integer.parseInt(paramMap.get("saveMark").toString()) == 0){
				//查询所有非预置进去的课程信息
				list = chapterDao.getAfterSaveChapter(paramMap);
			}
		}catch(Exception e){
			logger.error("查询课程及每个课程的章节信息getCourseList", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 查询所有非预置的课程，以及当前教师的添加的没关联课程的章节信息
	 * @param paramMap Map<String,Object>
	 * @return List
	 * @throws Exception
	 */
	public Map<String,Object> getNoInCourseList(Map<String, Object> paramMap, HttpServletRequest req) throws Exception{
		Map<String,Object> resulMap = Maps.newHashMap();
		try{
			//查询非预置全部课程
			List<Map<String, Object>> courseList = courseDao.getAllCourseMy(paramMap);
			//查询每个课程里面的章节信息
			if(courseList != null) {
				for (Map<String, Object> map : courseList) {
					//查询这个课程下的章节信息只要id名字，num
					List<Map<String, Object>> chapterList = chapterDao.getCourseChapter(map);
					map.put("chapterList", chapterList);
				}
				//全部非预置课程以及章节信息
				resulMap.put("courseList", courseList);
				//查询这个教师录入的章节列表信息
				//获取登录人信息
				Map<String, Object> sessionValues = new SessionValues().getSessionValues(new String[]{"stuorteaId"}, req, "userMsg");
				resulMap.put("myChapterList", courseDao.getMyInChaptersNoRelation(sessionValues));
			}
		}catch(Exception e){
			logger.error("查询所有非预置的课程异常getNoInCourseList", e);
			e.printStackTrace();
			return Maps.newHashMap();
		}
		return resulMap;
	}

	/**
	 * @description 判断这个数组里面是否有重复的值
	 * @param paramList 要验证的数组
	 * @param column 要判断的列值
	 * */
	public boolean checkRepeatFunc(Object paramList, String column) throws Exception{

		Set<Object> set = new HashSet<Object>();
		int paramSize = 0;
		try{
			if(column.equals("")){
				paramSize = ((List<Object>)paramList).size();
				for(Object obj : (List<Object>)paramList){
					set.add(obj);
				}
			}else{
				paramSize = ((List<Map<String, Object>>)paramList).size();
				for(Object map : (List<Map<String, Object>>)paramList){
					set.add(((Map<String, Object>)map).get(column));
				}
			}
			//有重复
			if(set.size() != paramSize){
				return false;
				//不重复
			}else{
				return true;
			}
		}catch(Exception e){
			logger.error("工具方法异常checkRepeatFunc", e);
			throw e;
		}
	}

	/**
	 * @description 下载课程的每个类型课件的方法，
	 * @param jsonStr ={"courseId":课程id，"downloadType":下载类型：1课件，2实验手册，3备课材料，4作业及作业答案 5视频 6课程材料}
	 * @param req
	 * @param res
	 * @return map中get：result,true成功，false失败
	 *         如果是失败的，从map中get出errorMsg，是失败信息。
	 */
	public void downloadCourseFileFunc(String jsonStr, HttpServletRequest req, HttpServletResponse res)  {
		//获取参数
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//通过课程id及要查询的类型的参数将所有文档以及他们文件的前缀拼接好弄出来得到一个String[] file 数组（里面都是文件的全路径）
			//获取文件前缀
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", new String[] {"server_address", "project_name","tomcatUrl"});
			String url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/course/";
			String downUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/course/";
			if(Integer.parseInt(String.valueOf(paramMap.get("downloadType")))==7){
				//通过课程id查询课程信息
				Map<String,Object> courseMap = courseDao.getCourseDetail(paramMap);
				//说明下载的是word资源，不需要后台打包
				String courseWordPack = null;
				int wordMark = 1;
				if(courseMap.get("courseWordPack")!=null&&!String.valueOf(courseMap.get("courseWordPack")).equals("")){
					wordMark = 0;
					courseWordPack = String.valueOf(courseMap.get("courseWordPack"));
				}
				downUrl = downUrl+courseWordPack;
				responseStream(res,"{\"result\":\"success\",\"url\":\""+downUrl+"\",\"wordMark\":\"" + wordMark+ "\"}");

			}else{
				//获取所有文件
				String[] filesArr = this.getCourseFileByType(paramMap, url);
				logger.info("批量下载课件信息，得到的文件集合为："+Arrays.toString(filesArr));
				if(filesArr != null && filesArr.length != 0){
					//年月日-课程名-类型名
					String fileName = DateUtil.getDateStr(new Date(),"yyyy年MM月dd日-HH时mm分ss秒")+"-"+courseDao.getCourseDetail(paramMap).get("courseName")+"-"+this.getTypeName(paramMap,"downloadType", new int[] {1,2,3,4,5,6}, new String[] {"课件","实验手册","备课材料","作业及作业答案","视频","课程材料"});
					FileDownloadZipUtil.downloadZipUtil(fileName,url+"download" , filesArr, req, res);
					responseStream(res,"{\"result\":\"success\",\"url\":\""+downUrl+"download"+"/"+new SessionValues().getSessionValues(new String[] {"stuorteaId"},req, "userMsg").get("stuorteaId").toString()+"/"+fileName+".zip"+"\",\"wordMark\":\"" + 0 + "\"}");
				}else{
					responseStream(res,"{\"result\":\"error\",\"failMsg\":\"暂无课件信息\"}");
				}
				logger.info("下载课程课件信息，参数为："+jsonStr);
			}

		}catch(FileNotFoundException fe){
			fe.printStackTrace();
			logger.error("下载课件信息操作，找不到课件文件错误.", fe);
			responseStream(res,"{\"result\":\"error\",\"failMsg\":\"课件文件无法获取，下载失败\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			logger.error("下载课程课件信息异常downloadCourseFileFunc", e);
			responseStream(res,"{\"result\":\"error\",\"failMsg\":\"下载错误\"}");
		}
	}

	/**
	 *@description  通过类型获取文件名信息
	 * @param "downloadType":下载类型：1课件，2实验手册，3备课材料，4作业及作业答案 5视频 }
	 * @param key 要获取的key
	 * @param markArr 数值对应的list
	 * @param wordArr 对应的文字信息list
	 * */
	public String getTypeName(Map<String, Object> paramMap, String key, int[] markArr, String[] wordArr){
		String result = "";
		int downloadType = Integer.parseInt(paramMap.get(key).toString());
		for(int i = 0; i < markArr.length; i++){
			if(downloadType == markArr[i]){
				return wordArr[i];
			}
		}
		return result;
	}


	/**
	 * @description 通过课程id及要查询的类型的参数将所有文档以及他们文件的前缀拼接好弄出来得到一个String[] file 数组（里面都是文件的全路径）
	 * @param paramMap  {"courseId":课程id，"downloadType":下载类型：1课件，2实验手册，3备课材料，4作业及作业答案 5视频 }
	 * @param path 所有文件前缀  eg:d:/123/
	 * @return String[] fileArr 保存的是所有文件的全路径
	 */
	public String[] getCourseFileByType(Map<String, Object> paramMap, String path) throws Exception {
		paramMap.put("path", path);
		//通过课程id及类型从数据库中查询出来所有这个类型的文件信息集合，并将文件前缀作为参数放入进行拼接
		ArrayList<String> fileList = (ArrayList<String>) courseDao.getCourseFileByType(paramMap);
		String[] strings = new String[fileList.size()];
		return fileList.toArray(strings);
	}

	/**
	 * @description 通过课程id及教师工号查询各自的简介信息
	 * @param jsonStr paramMap  stuorteaId   courseId
	 * @return
	 */
	public void getIntroctionByIds(String jsonStr, HttpServletRequest req, HttpServletResponse res) {
		//获取参数
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//获取课程简介信息
			Map<String, Object> courseDetail = courseDao.getCourseDetail(paramMap);
			//获取教师信息
			paramMap.put("selecetRoleId",2);
			Map<String, Object> stuDetail = memberDao.getMemberDetailById(paramMap).get(0);
			//构造数据
			paramMap = putDataToMap(paramMap, new Object[] {stuDetail,courseDetail}, new String[][] {{"userContect"},{"courseIntroduction"}});
			//写回页面
			responseStream(res, mapper.writeValueAsString(paramMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取课程及教师简介异常getIntroctionByIds", e);
			responseStream(res, "{\"result\":\"error\",\"failMsg\":\"系统错误\"}");
		}
	}

	/**
	 * @description 用于请求流写回页面
	 * @param res 返回流
	 * @param data 返回的数据
	 * */
	public void responseStream(HttpServletResponse res, String data){
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter write = null;
		try {
			if(data.equals("")){
				data = "{\"result\":\"error\"}";
			}
			write = res.getWriter();
		} catch (Exception e) {
			logger.error("流返回页面异常responseStream", e);
			e.printStackTrace();
		}
		write.println(data);
		write.flush();
	}

	/**
	 * @description 验证参数是否合格的方法
	 * */
	public boolean paramCheck(Object chapterName, HttpServletResponse response, Map<String, Object> resultMap, ObjectMapper mapper) throws JsonProcessingException {
		if(ParamConvertUtil.getMapDataSprcialMark(chapterName)){
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "参数含有特殊字符");
			responseStream(response, mapper.writeValueAsString(resultMap));
			return true;
		}
		return false;
	}

	/**
	 * @description 获取map中参数是否含有特殊字符
	 * */
	public boolean getMapSpecialMark(HttpServletResponse response, ObjectMapper mapper, Map<String, Object> resultMap, Map<String, Object> paramMap) throws JsonProcessingException {
		if(ParamConvertUtil.getSpecialWordMark(paramMap)){
			resultMap.put("result", "fail");
			resultMap.put("failMsg", "参数含有特殊字符");
			responseStream(response, mapper.writeValueAsString(resultMap));
			return true;
		}
		return false;
	}

	/**
	 * @description 将某些map中的数据放入某个mao中
	 * @param returnMap 要放入的map
	 * @param operateMapList 要操作的map集合，
	 *@param getColumn 每个map中要取的数据字段
	 * */
	public Map<String, Object> putDataToMap(Map<String, Object> returnMap, Object[] operateMapList, String[][] getColumn){
		for(int i = 0; i < operateMapList.length; i++){
			for(int j = 0; j < getColumn[i].length; j++){
				for(String col : getColumn[i]){
					returnMap.put(col, ((Map<String, Object>)operateMapList[i]).get(col));
				}
			}
		}
		return returnMap;
	}

	/**
	 * @description 通过课程id获取不能下载的类型的课件信息
	 *
	 * */
	public void getCantLoadMark(String jsonStr , HttpServletResponse response){
		List<Integer> list = new ArrayList<Integer>();
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		try {
			map = mapper.readValue(jsonStr, map.getClass());
			map.put("path", "test");
			//6种类型20180926加了个word资源下载
			for (int i = 1; i <= 6; i++) {
				map.put("downloadType", i);
				List<String> useList = courseDao.getCourseFileByType(map);
				if(useList == null || useList.size() == 0){
					list.add(i);
				}
			}
			//判断word资源这个课是否存在
			/*Map<String,Object> courseMap = courseDao.getCourseDetail(map);
			if(courseMap.get("courseWordPack")==null||String.valueOf(courseMap.get("courseWordPack")).equals("")){
				list.add(7);
			}*/
			map.put("result","success");
			map.put("cantDownList", list);
			responseStream(response, mapper.writeValueAsString(map));
		}catch(Exception e){
			e.printStackTrace();
			map.put("result","fail");
			try {
				responseStream(response, mapper.writeValueAsString(map));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * @description 通过教师号获取此教师所属课程(教的未结课的课程 sy)
	 * @param  paramMap Map<String,Object>
	 * @return List courseId课程id courseName课程名称
	 * @throws Exception
	 */
	public List<Map<String,Object>> getTeaTeachCourseByNoEnd(Map<String, Object> paramMap) throws Exception{

		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try{
			list = courseDao.getTeaTeachCourseByNoEnd(paramMap);
		}catch(Exception e){
			logger.error("通过教师号获取此教师所属课程(教的未结课的课程)getTeaTeachCourseByNoEnd", e);
			throw e;
		}
		return list;
	}

	/**
	 * @description 发布课程
	 * @param  paramMap list[courseId]
	 * @return Map<String,Object>
	 * @throws Exception
	 */
	public Map<String, Object> releaseCourse(Map<String, Object> paramMap) throws Exception {
		boolean flag = false;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<String> courseIdList = (List<String>) paramMap.get("list");
			if(courseIdList !=null && courseIdList.size()!=0){
				if(Integer.parseInt(String.valueOf(paramMap.get("releaseMark")))==0){
					//说明是取消发布，判断要取消的课程中是否存在学习记录
					List<Map<String, Object>> relationList = relationDao.getDelCourseMark(courseIdList);
					if(relationList != null && relationList.size() != 0){
						//说明有学习记录，不可以取消发布
						map.put("result", false);
						map.put("failMsg", "已有学习记录不可取消发布");
						return map;
					}
				}
				flag = courseDao.releaseCourse(paramMap);
				map.put("failMsg", "");
				map.put("result", flag);
			}else{
				map.put("result", false);
				map.put("failMsg", "参数不正确");
			}
			logger.info("发布课程参数为："+courseIdList);
		} catch (Exception e) {
			throw e;
		}
		return map;
	}

	/**
	 * @description 分享课程
	 * @param  paramMap list[courseId],shareMark 0取消 1分享
	 * @return Map<String,Object>
	 * @throws Exception
	 */
	public Map<String, Object> shareCourse(Map<String, Object> paramMap,HttpServletRequest request) throws Exception {
		boolean flag = false;
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String stuorteaId = PubMethods.loginId(request);
			if(Integer.parseInt(String.valueOf(paramMap.get("shareMark")))==0){
				//获取当前登录人要取消分享课程所用有的章节集合
				paramMap.put("stuorteaId",stuorteaId);
				/**20180828白哥说将取消分享这部分不需要做是否课程被使用的校验**/
				/*List<Map<String,Object>> chapterList = courseDao.getShareChapter(paramMap);
				if(chapterList!=null&&chapterList.size()!=0){
					//判断要取消分享的课程是否已经有人使用
					paramMap.put("chapterList",chapterList);
					List<Map<String,Object>> chapterListTwo = courseDao.getShareChapterByChapterName(paramMap);
					if(chapterListTwo!=null&&chapterListTwo.size()!=0){
						//说明已经有人用你分享的课程内容了，不可以取消
						map.put("result", false);
						map.put("failMsg", "课程已被使用，不可以取消分享");
						return map;
					}
				}*///else说明当前登录人要取消的课程还没有章节相当于别人也还没有用，则可以取消

			}
			List<String> courseIdList = (List<String>) paramMap.get("list");
			if(courseIdList !=null && courseIdList.size()!=0){
				flag = courseDao.shareCourse(paramMap);
				map.put("result", flag);
				map.put("failMsg", "");
			}else{
				map.put("result", false);
				map.put("failMsg", "参数不正确");
			}
			logger.info("分享课程参数为："+courseIdList);
		} catch (Exception e) {
			throw e;
		}
		return map;
	}

	@Transactional
	public String insertSkill(List<SkillDTO> list, Integer skillId, MultipartFile file, Integer role) {

		//level 1
		try {
			SkillNotes skillDTOnew0 = new SkillNotes();
			skillDTOnew0.setLevel(1);
			skillDTOnew0.setName(list.get(0).getPost());
			skillDTOnew0.setCreateTime(new Date());
			Integer id = courseDao.insertSkill(skillDTOnew0);
			//level 2
			SkillNotes skillDTOnew1 = new SkillNotes();
			skillDTOnew1.setLevel(2);
			skillDTOnew1.setParentId(skillDTOnew0.getId());
			skillDTOnew1.setName(list.get(0).getDescribe());
			skillDTOnew1.setCreateTime(new Date());
			courseDao.insertSkill(skillDTOnew1);
			//level 3
			int count = 0;
			Map<String, Integer> map = new HashMap<String, Integer>();
			for (SkillDTO skillDTO : list) {
				count++;
				if (!"".equals(skillDTO.getSkillModule())) {
					SkillNotes skillDTOnew2 = new SkillNotes();
					skillDTOnew2.setLevel(3);
					skillDTOnew2.setParentId(skillDTOnew1.getId());
					skillDTOnew2.setName(skillDTO.getSkillModule());
					skillDTOnew2.setCreateTime(new Date());
					courseDao.insertSkill(skillDTOnew2);
					map.put(StringUtils.join(count), skillDTOnew2.getId());
				}
			}
			Map map4 = querySkillStutas(map, list.size() + 1);
			//level 4
			Map<String, Integer> map1 = new HashMap<String, Integer>();
			int count1 = 0;
			for (SkillDTO skillDTO : list) {
				count1++;
				if (!"".equals(skillDTO.getSubSkill())) {
					SkillNotes skillDTOnew3 = new SkillNotes();
					skillDTOnew3.setLevel(4);
					skillDTOnew3.setParentId(queryParentId(map4, count1));
					skillDTOnew3.setName(skillDTO.getSubSkill());
					courseDao.insertSkill(skillDTOnew3);
					map1.put(StringUtils.join(count1), skillDTOnew3.getId());
				}
			}
			Map map5 = querySkillStutas(map1, list.size() + 1);
			//level 5
			int count2 = 0;
			Map<String, Integer> map2 = new HashMap<String, Integer>();
			for (SkillDTO skillDTO : list) {
				count2++;
				if (!"".equals(skillDTO.getKnowledgePoints())) {
					SkillNotes skillDTOnew4 = new SkillNotes();
					skillDTOnew4.setLevel(5);
					skillDTOnew4.setParentId(queryParentId(map5, count2));
					skillDTOnew4.setName(skillDTO.getKnowledgePoints());
					courseDao.insertSkill(skillDTOnew4);
					map2.put(StringUtils.join(count2), skillDTOnew4.getId());
				}
			}
			Map map6 = querySkillStutas(map2, list.size() + 1);
			//level 6
			int count3 = 0;
			for (SkillDTO skillDTO : list) {
				count3++;
				if (!"".equals(skillDTO.getKnowledgePoints())) {
					SkillNotes skillDTOnew5 = new SkillNotes();
					skillDTOnew5.setLevel(6);
					skillDTOnew5.setParentId(queryParentId(map6, count3));
//					List<Map<String, Object>> listmap = courseDao.querySkillCourse(null, skillDTO.getCourseName());
					String idnew = "0";
					String key_value = "";
					skillDTOnew5.setIconValue(key_value);
					skillDTOnew5.setCourseId(Integer.valueOf(idnew));
					skillDTOnew5.setName(skillDTO.getCourseName());
					courseDao.insertSkill(skillDTOnew5);

				}
			}

			return "";
		} catch (Exception e) {
			System.out.println(e.getMessage());
			throw new GlobalException(com.hrbxlh.virtualization.result.ResultEnum.SERVER_ERROR);

		}

	}

	public Map querySkillStutas(Map<String, Integer> map, Integer count) {
		Map<String, Integer> mapnew = map.entrySet()
				.stream()
				.sorted(Map.Entry.comparingByValue())
				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
		List list = Lists.newArrayList();
		for (String key : mapnew.keySet()) {
			list.add(key);
		}
		list.add(count);
		String countold = "";
		Map map1 = new HashMap();
		if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) {
			for (int i = 0; i < 1; i++) {
				for (int j = 1; j < list.size(); j++) {
					if (j == 1) {
						map1.put(list.get(i).toString() + "-" + list.get(j).toString(), mapnew.get(list.get(i).toString()));
					} else {
						if (Integer.valueOf(list.get(j).toString()) == count) {
							map1.put(countold + "-" + list.get(j).toString(), mapnew.get(countold));
						} else {
							map1.put(countold + "-" + list.get(j).toString(), mapnew.get(countold));
						}
					}
					countold = list.get(j).toString();
				}
			}
		}
		return map1;
	}

	private Integer queryParentId(Map<String, Integer> map, Integer count) {
		Integer value = null;
		for (String countnew : map.keySet()) {
			String[] split = countnew.split("-");
			if (Integer.valueOf(split[1]) == 1 && count == 1) {
				value = Integer.valueOf(map.get(countnew).toString());
			} else {
				for (int i = Integer.valueOf(split[0]); i < Integer.valueOf(split[1]); i++) {
					if (count == i) {
						value = Integer.valueOf(map.get(countnew).toString());
					}
				}
			}
		}
		return value;
	}

	public List<SkillNotes> querySkill(Integer id) {
		List<SkillNotes> childLists = null;
		childLists = courseDao.getChildLists(id);
		if (id == null) {
			childLists = courseDao.getChildListsnew();
		}
		return childLists;
	}

	public void updateSkill(Integer id, String name) {
		courseDao.updateSkill(name, id, null);
	}
	public Map<String, List<SkillNotes>> querySkillOther(Integer id) {

		List<SkillNotes> childLists = courseDao.getChildLists(id);
		if (childLists != null && childLists.size() > 0 && childLists.get(0).getChildrenList() != null && childLists.get(0).getChildrenList().size() > 0) {
			List<SkillNotes> childrenList = childLists.get(0).getChildrenList();
			List<SkillNotes> childrenList1 = childrenList.get(0).getChildrenList();
			Map map = new HashMap();
			for (SkillNotes skillNotes : childrenList1) {
				List<SkillNotes> list = Lists.newArrayList();
				if (skillNotes.getChildrenList().size() > 0) {
					List<SkillNotes> skillNotes3 = querySkillInfoOther(skillNotes.getChildrenList());
					for (SkillNotes skillNotes1 : skillNotes3) {
						if (skillNotes1 != null && skillNotes1.getChildrenList().size() > 0 && skillNotes1.getChildrenList().get(0).getChildrenList().size() > 0) {
							SkillNotes skillNotes2 = new SkillNotes();
							String courseName = skillNotes1.getChildrenList().get(0).getChildrenList().size() == 0 ? "" : skillNotes1.getChildrenList().get(0).getChildrenList().get(0).getName();
							skillNotes2.setName(skillNotes1.getChildrenList().get(0).getChildrenList().size() == 0 ? "" : skillNotes1.getChildrenList().get(0).getChildrenList().get(0).getName());
							skillNotes2.setIconValue("");
							list.add(skillNotes2);
						}
					}
				}
				map.put(skillNotes.getId(), list);

			}
			return map;
		}
		return null;
	}
	private List<SkillNotes> querySkillInfoOther(List<SkillNotes> skillNoteslist) {
		// 从list中索引为0开始往后遍历
		for (int i = 0; i < skillNoteslist.size() - 1; i++) {
			// 从list中索引为 list.size()-1 开始往前遍历
			for (int j = skillNoteslist.size() - 1; j > i; j--) {
				// 进行比较
				if (skillNoteslist.get(j).getChildrenList().size() > 0 && skillNoteslist.get(j).getChildrenList().get(0).getChildrenList().size() > 0 && skillNoteslist.get(i).getChildrenList().size() > 0 && skillNoteslist.get(i).getChildrenList().get(0).getChildrenList().size() > 0) {
					if (skillNoteslist.get(j).getChildrenList().get(0).getChildrenList().get(0).getName().equals(skillNoteslist.get(i).getChildrenList().get(0).getChildrenList().get(0).getName())) {
						// 去重
						skillNoteslist.remove(j);
					}
				}
			}
		}
		return skillNoteslist;
	}
}